package com.mondo.financialwallet.presentation.ui.fragment;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.common.ui.AbsNetworkStateFragment;
import com.example.common.widget.state.NetworkStateLayout;
import com.github.mikephil.charting.charts.LineChart;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.data.entity.HoldProductListEntity;
import com.mondo.financialwallet.data.entity.HoldProductProfitDataEntity;
import com.mondo.financialwallet.data.entity.UserAssetsEntity;
import com.mondo.financialwallet.presentation.model.ProductProfitDataModel;
import com.mondo.financialwallet.presentation.event.RequestHoldProductEvent;
import com.mondo.financialwallet.presentation.event.RequestUserAssetEvent;
import com.mondo.financialwallet.presentation.ui.adapter.HoldProductAdapter;
import com.mondo.financialwallet.presentation.model.HoldProduct;
import com.mondo.financialwallet.presentation.ui.activity.HoldProductDetailsActivity;
import com.mondo.financialwallet.presentation.utils.LineChartUtils;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;

/**
 * 理财产品, 持有
 */
public class HoldProductFragment extends AbsNetworkStateFragment implements BaseQuickAdapter.OnItemClickListener {

    @Bind(R.id.hold_product_list) RecyclerView mHoldProductList;
    @Bind(R.id.total_assets_text_view) TextView mTotalAssetsTextView;
    @Bind(R.id.cumulative_income_text) TextView mCumulativeIncomeText;
    @Bind(R.id.yesterday_earnings_text) TextView mYesterdayEarningsText;
    @Bind(R.id.hold_product_state_layout) NetworkStateLayout mHoldProductStateLayout;
    @Bind(R.id.product_income_line_chart) LineChart mProductIncomeLineChart;
    @Bind(R.id.product_income_state_layout) NetworkStateLayout mProductIncomeStateLayout;

    private HoldProductAdapter mAdapter;

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected int getLayoutID() {
        return R.layout.fragment_hold_product;
    }

    @Override
    protected void initActions() {
        // 持有产品
        mAdapter = new HoldProductAdapter();
        mAdapter.setOnItemClickListener(this);
        mHoldProductList.setAdapter(mAdapter);

        // 用户资产, 产品收益
        requestUserAsset();

        // 持有产品列表
        requestHoldProductList();

        // 请求收益数据
        requestHoldProductProfitData();
    }

    private void requestHoldProductProfitData(){
        mProductIncomeStateLayout.loadingNetwork();

        DataRepository.get().holdProductProfitData("", result -> {
            if(result == null){
                mProductIncomeStateLayout.emptyNetwork();
                return;
            }

            if (result.isSuccess()) {
                mProductIncomeStateLayout.successNetwork();
                List<List<HoldProductProfitDataEntity.DataBean>> data = result.getData();
                List<ProductProfitDataModel> list = new ArrayList<>();

                if(data != null && data.size() > 0){
                    List<HoldProductProfitDataEntity.DataBean> dataBeans = data.get(0);
                    for (HoldProductProfitDataEntity.DataBean dataBean : dataBeans) {
                        list.add(new ProductProfitDataModel(dataBean.getTotal_profit(), dataBean.getDate()));
                    }
                }

                // 收益图表
                LineChartUtils.init("累计收益", mProductIncomeLineChart, list);
            } else {
//                mProductIncomeStateLayout.errorNetwork(result.getMsg());
                mProductIncomeStateLayout.emptyNetwork();
            }
        });
    }

    private void requestHoldProductList() {
        mHoldProductStateLayout.loadingNetwork();
        DataRepository.get().holdProductList(result -> {
            if (result.isSuccess()) {
                mHoldProductStateLayout.successNetwork();
                HoldProductListEntity.DataBeanX data = result.getData();
                List<HoldProductListEntity.DataBeanX.DataBean> dataList = data.getData();
                if(dataList == null || dataList.isEmpty()){
                    mHoldProductStateLayout.emptyNetwork();
                    return;
                }

                List<HoldProduct> holdProductList = new ArrayList<>();
                for (HoldProductListEntity.DataBeanX.DataBean bean : dataList) {
                    if (bean.getStatusX() == 3) {
                        holdProductList.add(new HoldProduct(
                                bean.getOrder_no(),
                                bean.getGoods_name(),
                                String.valueOf(bean.getHold_money()),
                                bean.getExpire_day() + "天",
                                bean.getGoods_profit()
                        ));
                    }
                }

                mAdapter.setNewData(holdProductList);
            } else {
                mHoldProductStateLayout.errorNetwork(result.getMsg());
            }
        });
    }

    private void requestUserAsset(){
        DataRepository.get().userAssets(result -> {
            UserAssetsEntity.DataBean asset = result.getData();
            mTotalAssetsTextView.setText(asset.getFund_asset());        // 总理财收益
            mYesterdayEarningsText.setText(asset.getYesterday_profit());// 昨日收益
            mCumulativeIncomeText.setText(asset.getProfit());   // 累积收益
        });
    }

    @Override
    public void onAnewRequest() {
        requestUserAsset();
        requestHoldProductList();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        HoldProduct item = (HoldProduct) adapter.getItem(position);
        HoldProductDetailsActivity.launch(view.getContext(), item);
    }

    @Subscribe
    public void requestHoldProductEvent(RequestHoldProductEvent event){
        requestHoldProductList();
    }

    @Subscribe
    public void requestUserAssetEvent(RequestUserAssetEvent event){
        requestUserAsset();
    }
}
